package servlets;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.Person;
import dal.Crud;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public LoginServlet() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		if (request.getSession().getAttribute("userId") == null) {
			getServletContext().getRequestDispatcher("/pages/login.jsp")
					.forward(request, response);
		} else {
			getServletContext().getRequestDispatcher("/").forward(request,
					response);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String email = request.getParameter("email");
		String password = request.getParameter("password");

		try {
			Crud c = new Crud();
			Person p = c.getPerson(email, password);

			if (p == null) {
				getServletContext().getRequestDispatcher("/Login").forward(
						request, response);
			} else {
				HttpSession session = request.getSession();
				session.setAttribute("userName",
						p.getFirstName() + " " + p.getLastName());

				session.setAttribute("userId", p.getId());

				getServletContext().getRequestDispatcher("/").forward(request,
						response);
			}
		} catch (Exception e) {
			response.getOutputStream().write(e.toString().getBytes());
		}
	}

}
